/**
  ******************************************************************************
  * @file    IAP/src/common.c 
  * @author  MCD Application Team
  * @version V3.3.0
  * @date    10/15/2010
  * @brief   This file provides all the common functions.
  ******************************************************************************
  * @copy
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2010 STMicroelectronics</center></h2>
  */ 

/** @addtogroup IAP
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include "common.h"
#include "ymodem.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

/* APP程序的复位中断向量函数指针 */
pFunction Jump_To_Application;
/* 跳转地址,APP程序的复位中断向量的地址 */
uint32_t JumpAddress;
/* flash掩码,用于判断是否有flash的扇区处于写保护状态 */
uint32_t  UserMemoryMask = 0;
/* flash扇区写保护标志位 */
__IO uint32_t FlashProtection = 0;
/* APP程序起始地址的对应扇区信息结构体 */
fmc_sector_info_struct start_sector;
/* APP程序结束地址的对应扇区信息结构体 */
fmc_sector_info_struct end_sector;

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Convert an Integer to a string
  * @param  str: The string
  * @param  intnum: The intger to be converted
  * @retval None
  */
void Int2Str(uint8_t* str, int32_t intnum)
{
  uint32_t i, Div = 1000000000, j = 0, Status = 0;

  for (i = 0; i < 10; i++)
  {
    str[j++] = (intnum / Div) + 48;

    intnum = intnum % Div;
    Div /= 10;
    if ((str[j-1] == '0') & (Status == 0))
    {
      j = 0;
    }
    else
    {
      Status++;
    }
  }
}

/**
  * @brief  Convert a string to an integer
  * @param  inputstr: The string to be converted
  * @param  intnum: The intger value
  * @retval 1: Correct
  *         0: Error
  */
uint32_t Str2Int(uint8_t *inputstr, int32_t *intnum)
{
  uint32_t i = 0, res = 0;
  uint32_t val = 0;

  if (inputstr[0] == '0' && (inputstr[1] == 'x' || inputstr[1] == 'X'))
  {
    if (inputstr[2] == '\0')
    {
      return 0;
    }
    for (i = 2; i < 11; i++)
    {
      if (inputstr[i] == '\0')
      {
        *intnum = val;
        /* return 1; */
        res = 1;
        break;
      }
      if (ISVALIDHEX(inputstr[i]))
      {
        val = (val << 4) + CONVERTHEX(inputstr[i]);
      }
      else
      {
        /* return 0, Invalid input */
        res = 0;
        break;
      }
    }
    /* over 8 digit hex --invalid */
    if (i >= 11)
    {
      res = 0;
    }
  }
  else /* max 10-digit decimal input */
  {
    for (i = 0;i < 11;i++)
    {
      if (inputstr[i] == '\0')
      {
        *intnum = val;
        /* return 1 */
        res = 1;
        break;
      }
      else if ((inputstr[i] == 'k' || inputstr[i] == 'K') && (i > 0))
      {
        val = val << 10;
        *intnum = val;
        res = 1;
        break;
      }
      else if ((inputstr[i] == 'm' || inputstr[i] == 'M') && (i > 0))
      {
        val = val << 20;
        *intnum = val;
        res = 1;
        break;
      }
      else if (ISVALIDDEC(inputstr[i]))
      {
        val = val * 10 + CONVERTDEC(inputstr[i]);
      }
      else
      {
        /* return 0, Invalid input */
        res = 0;
        break;
      }
    }
    /* Over 10 digit decimal --invalid */
    if (i >= 11)
    {
      res = 0;
    }
  }

  return res;
}

/**
  * @brief  Get an integer from the HyperTerminal
  * @param  num: The inetger
  * @retval 1: Correct
  *         0: Error
  */
uint32_t GetIntegerInput(int32_t * num)
{
  uint8_t inputstr[16];

  while (1)
  {
    GetInputString(inputstr);
    if (inputstr[0] == '\0') continue;
    if ((inputstr[0] == 'a' || inputstr[0] == 'A') && inputstr[1] == '\0')
    {
      SerialPutString("User Cancelled \r\n");
      return 0;
    }

    if (Str2Int(inputstr, num) == 0)
    {
      SerialPutString("Error, Input again: \r\n");
    }
    else
    {
      return 1;
    }
  }
}

/**
  * @brief  Test to see if a key has been pressed on the HyperTerminal
  * @param  key: The key pressed
  * @retval 1: Correct
  *         0: Error
  */
uint32_t SerialKeyPressed(uint8_t *key)
{
  if(usart_flag_get(USART0, USART_FLAG_RBNE) != RESET)
  {
    *key = (uint8_t)usart_data_receive(USART0);
    return 1;
  }
  else
  {
    return 0;
  }
}

/**
  * @brief  Get a key from the HyperTerminal
  * @param  None
  * @retval The Key Pressed
  */
uint8_t GetKey(void)
{
  uint8_t key = 0;

  /* Waiting for user input */
  while (1)
  {
    if (SerialKeyPressed((uint8_t*)&key)) break;
  }
  return key;

}

/**
  * @brief  Print a character on the HyperTerminal
  * @param  c: The character to be printed
  * @retval None
  */
void SerialPutChar(uint8_t c)
{
  usart_data_transmit(USART0, c);
  while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
}

/**
  * @brief  Print a string on the HyperTerminal
  * @param  s: The string to be printed
  * @retval None
  */
void Serial_PutString(uint8_t *s)
{
  while (*s != '\0')
  {
    SerialPutChar(*s);
    s++;
  }
}

/**
  * @brief  Get Input string from the HyperTerminal
  * @param  buffP: The input string
  * @retval None
  */
void GetInputString (uint8_t * buffP)
{
  uint32_t bytes_read = 0;
  uint8_t c = 0;
  do
  {
    c = GetKey();
    if (c == '\r')
      break;
    if (c == '\b') /* Backspace */
    {
      if (bytes_read > 0)
      {
        SerialPutString("\b \b");
        bytes_read --;
      }
      continue;
    }
    if (bytes_read >= CMD_STRING_SIZE )
    {
      SerialPutString("Command string size overflow\r\n");
      bytes_read = 0;
      continue;
    }
    if (c >= 0x20 && c <= 0x7E)
    {
      buffP[bytes_read++] = c;
      SerialPutChar(c);
    }
  }
  while (1);
  SerialPutString(("\n\r"));
  buffP[bytes_read] = '\0';
}


/**
  * @brief  禁用用户内存区域的写保护功能。
  * @param  无
  * @retval 无
  * 
  * 该函数用于检查并解除Flash中用户内存区域的写保护设置。如果检测到写保护已启用，
  * 则会擦除选项字节，并重新配置写保护寄存器以禁用写保护。同时恢复用户选项字节配置，
  * 如独立看门狗选择、深度睡眠复位配置和待机模式复位配置。
  * 若操作成功，则触发系统复位以加载新的选项字节；若失败，则输出错误信息。
  */
void FLASH_DisableWriteProtectionPages(void)
{
  uint32_t useroptionbyte = 0, WRPR = 0;
  uint16_t var1 = OB_FWDGT_SW, var2 = OB_DEEPSLEEP_NRST, var3 = OB_STDBY_NRST;
  ErrStatus status;

  /* 在GD32中,如果FLASH容量大于等于512KB,系统会将其flash分为两个块:块0与块1
   * 由于F407VET6恰好为512KB,根据用户手册,可得知使用的是块0 */
  WRPR = ob_write_protection0_get();

  /* Test if user memory is write protected */
  if ((WRPR & UserMemoryMask) != UserMemoryMask)
  {
    useroptionbyte = ob_user_get();

    UserMemoryMask |= WRPR;

    ob_erase();

    if (UserMemoryMask != 0xFFFFFFFF)
    {
       status = ob_write_protection_enable((uint32_t)~UserMemoryMask);
    }

    /* Test if user Option Bytes are programmed */
    if ((useroptionbyte & 0x07) != 0x07)
    { 
      /* Restore user Option Bytes */
      if ((useroptionbyte & 0x01) == 0x0)
      {
        var1 = OB_FWDGT_HW;
      }
      if ((useroptionbyte & 0x02) == 0x0)
      {
        var2 = OB_DEEPSLEEP_RST;
      }
      if ((useroptionbyte & 0x04) == 0x0)
      {
        var3 = OB_STDBY_RST;
      }

      ob_user_write(var1, var2, var3);
    }

    if (status == ERROR)
    {
      SerialPutString("Write Protection disabled...\r\n");

      SerialPutString("...and a System Reset will be generated to re-load the new option bytes\r\n");

      /* Generate System Reset to load the new option byte values */
      NVIC_SystemReset();
    }
    else
    {
      SerialPutString("Error: Flash write unprotection failed...\r\n");
    }
  }
  else
  {
    SerialPutString("Flash memory not write protected\r\n");
  }
}

/*!
 * \brief 主菜单函数，提供用户交互界面，用于下载、上传、执行程序或解除写保护
 * 该函数显示主菜单选项，等待用户输入，并根据输入执行相应的操作：
 * - 下载镜像到内部 Flash
 * - 从内部 Flash 上传镜像
 * - 执行新下载的应用程序
 * - 若存在写保护，则提供解除写保护选项
 * \param 无
 * \return 无
 */
void Main_Menu(void)
{
  uint8_t key = 0;
  /* Compute the mask to test if the Flash memory, where the user program will be
     loaded, is write protected */
	
	  // 获取程序起始地址所在的扇区结构体句柄
    start_sector = fmc_sector_info_get(ApplicationAddress);
	  // 获取程序结束地址所在的扇区结构体句柄
	  end_sector = fmc_sector_info_get(ApplicationEndAddress);
	
    // 程序占用的扇区范围:从start_sector.sector_num到end_sector.sector_num
    uint8_t start_num = start_sector.sector_num;
    uint8_t end_num = end_sector.sector_num;

    for (uint8_t i = start_num; i <= end_num; i++) 
    {
      UserMemoryMask |= (1 << i);  // 每个扇区对应1个bit位
    }
	
    /* 测试APP程序将被加载的闪存扇区中是否有任何扇区处于写保护状态 */
    if ((ob_write_protection0_get() & UserMemoryMask) != UserMemoryMask) 
        FlashProtection = 0;  /* 没有扇区处于写保护状态 */
    else 
        FlashProtection = 1;  /* 有扇区处于写保护状态 */
	

    while (1)
    {
        SerialPutString("1. Download APP  \r\n");
        SerialPutString("2. Upload APP \r\n");
        SerialPutString("3. Running APP  \r\n");
        
        if(FlashProtection != 0)
        {
          SerialPutString("4. Disable write protection  \r\n");
        }
        
        /* 获取输入的数字 */
        key = GetKey();

        if (key == 0x31)//输入1
        {
            /* 下载用户程序到flash */
            SerialDownload();
        }
        else if (key == 0x32)//输入2
        {
            /* 从 Flash 上传用户应用程序 */
            SerialUpload();
        }
        else if (key == 0x33)//输入3,跳转到用户程序
        {
            Jump_to_APP_Program();
        }
        else if ((key == 0x34) && (FlashProtection == 1))//输入4
        {
            /* 解除flash写保护 */
            FLASH_DisableWriteProtectionPages();
        }
        else
        {
            if (FlashProtection == 0)
            {
                SerialPutString("Invalid Number ! ==> The number should be either 1, 2 or 3\r");
            }
            else
            {
                SerialPutString("Invalid Number ! ==> The number should be either 1, 2, 3 or 4\r");
            }
        }
    }
}

void Jump_to_APP_Program(void)
{
		/* 关闭中断,跳转过程中不允许被中断打断 */
		__disable_irq();
	
		/* 写入标志位,下次启动时将不进入BootLoader而是直接运行APP */
		int32_t Data = FLAG_ENTER_APP;
		fmc_write_32bit_data(BOOT_FLAG_ADDR, 1, &Data);
	
		/* 由于APP存储位置偏移,对应中断向量表也需要偏移相同位置 */
		nvic_vector_table_set(NVIC_VECTTAB_FLASH, (ApplicationAddress - FLASH_BASE));

		/* 获取跳转地址,其实就是APP程序对应的复位中断向量的地址 */
		JumpAddress = *(__IO uint32_t*) (ApplicationAddress + 4);

		/* 函数指针赋值 */
		Jump_To_Application = (pFunction) JumpAddress;

		/* 初始化APP程序的MSP指针 */
		__set_MSP(*(__IO uint32_t*) ApplicationAddress);

		/* 恢复中断 */
		__enable_irq();

		/* 跳转到APP程序 */
		Jump_To_Application();
}
/**
  * @}
  */

/*******************(C)COPYRIGHT 2010 STMicroelectronics *****END OF FILE******/
